package com.shj.em.aa.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.shj.em.aa.dto.RoleSearchDTO;
import com.shj.em.aa.entity.Role;
import com.shj.em.aa.mapper.RoleMapper;
import com.shj.em.base.exception.BizException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * <p>
 * 角色 服务实现类
 * </p>
 *
 * @author Shen Huang Jian
 * @since 2018-06-25
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    public Set<Role> findRolesByUserLoginId(String userLoginId){
        return roleMapper.findRolesByUserLoginId(userLoginId);
    }

    public List<Role> findRolesByUserId(Long userId){
        return roleMapper.findRolesByUserId(userId);
    }

    public List<Role> findAllRoles(){
        Wrapper<Role> wrapper = new EntityWrapper<>();
        wrapper.eq("del_flag", 0);
        return roleMapper.selectList(wrapper);
    }

    public Page<Role> queryRolePage(RoleSearchDTO searchDTO){
        Page<Role> page = new Page<>(searchDTO.getPageNo(), searchDTO.getPageSize());
        List<Role> list = roleMapper.queryRolePage(page, searchDTO);
        return page.setRecords(list);
    }

    public boolean insertOrUpdate(Role role){
        Wrapper<Role> wrapper = new EntityWrapper<>();
        wrapper.eq("del_flag", 0).eq("role_name", role.getRoleName());
        if(role.getId() != null){
            wrapper.ne("id", role.getId());
        }
        if(role.getId() == null || role.getId() == -1L){
            role.setFixed(0);
            role.setRoleCode(null);
        }
        List<Role> list = roleMapper.selectList(wrapper);
        if(list == null || list.isEmpty()){
            return super.insertOrUpdate(role);
        }else{
            throw new BizException("角色名已存在");
        }
    }

}
